/**
 * API调用Hooks
 * 封装API调用逻辑，提供统一的状态管理和错误处理
 */

import { useState, useEffect, useCallback, useRef } from "react";
import { message } from "antd";
import {
  authAPI,
  classAPI,
  fileAPI,
  adviceAPI,
  examAPI,
  discussionAPI,
  aiAPI,
  dashboardAPI,
  healthAPI,
} from "../services/apiService";
import {
  LoginRequest,
  RegisterRequest,
  CreateClassRequest,
  AddFileRequest,
  AddAdviceRequest,
  AddExamRequest,
  AddTopicRequest,
  AddCommentRequest,
  CommonQueryParams,
} from "../types/api";
import { useUser } from "../contexts/UserContext";

// =============================================================================
// 基础Hook类型
// =============================================================================

interface UseAPIState<T> {
  data: T | null;
  loading: boolean;
  error: string | null;
}

interface UseAPIOptions {
  immediate?: boolean; // 是否立即执行
  showError?: boolean; // 是否显示错误消息
  showSuccess?: boolean; // 是否显示成功消息
  successMessage?: string; // 自定义成功消息
  requireAuth?: boolean; // 是否需要认证
}

// =============================================================================
// 基础API Hook
// =============================================================================

/**
 * 基础API调用Hook
 */
function useBaseAPI<T, P extends any[]>(
  apiFunction: (...params: P) => Promise<T>,
  options: UseAPIOptions = {}
) {
  const {
    immediate = false,
    showError = true,
    showSuccess = false,
    successMessage,
    requireAuth = true,
  } = options;

  const { isAuthenticated, loading: authLoading } = useUser();

  const [state, setState] = useState<UseAPIState<T>>({
    data: null,
    loading: false,
    error: null,
  });

  const abortControllerRef = useRef<AbortController | null>(null);

  const execute = useCallback(
    async (...params: P) => {
      // 如果需要认证但用户未登录，直接返回
      if (requireAuth && !isAuthenticated) {
        console.log("🔒 API需要认证但用户未登录，跳过执行");
        return;
      }

      // 取消之前的请求
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }

      abortControllerRef.current = new AbortController();

      setState((prev) => ({ ...prev, loading: true, error: null }));

      try {
        const result = await apiFunction(...params);

        setState({
          data: result,
          loading: false,
          error: null,
        });

        if (showSuccess) {
          message.success(successMessage || "操作成功");
        }

        return result;
      } catch (error: any) {
        const errorMessage = error.message || "操作失败";

        setState({
          data: null,
          loading: false,
          error: errorMessage,
        });

        if (showError && error.status !== 401) {
          // 401错误由认证系统统一处理，不显示重复错误
          message.error(errorMessage);
        }

        throw error;
      }
    },
    [
      apiFunction,
      showError,
      showSuccess,
      successMessage,
      requireAuth,
      isAuthenticated,
    ]
  );

  const reset = useCallback(() => {
    setState({
      data: null,
      loading: false,
      error: null,
    });
  }, []);

  useEffect(() => {
    // 只有在不需要认证或者已经认证且认证加载完成时才执行immediate请求
    if (immediate && (!requireAuth || (isAuthenticated && !authLoading))) {
      (execute as any)();
    }
    // 移除execute依赖项，避免无限循环
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [immediate, requireAuth, isAuthenticated, authLoading]);

  return {
    ...state,
    execute,
    reset,
  };
}

// =============================================================================
// 认证相关Hooks
// =============================================================================

/**
 * 登录Hook
 */
export function useLogin() {
  return useBaseAPI((data: LoginRequest) => authAPI.login(data), {
    showSuccess: true,
    successMessage: "登录成功",
    requireAuth: false, // 登录不需要认证
  });
}

/**
 * 注册Hook
 */
export function useRegister() {
  return useBaseAPI((data: RegisterRequest) => authAPI.register(data), {
    showSuccess: true,
    successMessage: "注册成功",
    requireAuth: false, // 注册不需要认证
  });
}

/**
 * 获取用户信息Hook
 */
export function useUserInfo(immediate = false) {
  return useBaseAPI(() => authAPI.getUserInfo(), {
    immediate,
    showError: false,
  });
}

/**
 * 发送验证码Hook
 */
export function useSendCode() {
  return useBaseAPI(
    (phone: string, captcha: string) => authAPI.sendCode({ phone, captcha }),
    {
      showSuccess: true,
      successMessage: "验证码发送成功",
      requireAuth: false, // 发送验证码不需要认证
    }
  );
}

// =============================================================================
// 班级管理Hooks
// =============================================================================

/**
 * 获取班级列表Hook
 */
export function useClasses(params?: CommonQueryParams, immediate = false) {
  return useBaseAPI(
    () => {
      console.log("🏫 useClasses 被调用:", { params, immediate });
      console.log("🔍 当前认证状态检查:");

      // 检查token
      const token =
        localStorage.getItem("authToken") ||
        sessionStorage.getItem("authToken");
      console.log("🔑 Token存在:", !!token);
      if (token) {
        console.log("🔑 Token前缀:", token.substring(0, 30) + "...");
      }

      return classAPI.getClasses(params);
    },
    { immediate }
  );
}

/**
 * 创建班级Hook
 */
export function useCreateClass() {
  return useBaseAPI((data: CreateClassRequest) => classAPI.createClass(data), {
    showSuccess: true,
    successMessage: "班级创建成功",
  });
}

/**
 * 获取班级详情Hook
 */
export function useClassInfo(classId?: number) {
  return useBaseAPI((id: number) => classAPI.getClassInfo(id), {
    immediate: !!classId,
  });
}

/**
 * 获取班级成员Hook
 */
export function useClassMembers(
  classId?: number,
  status: "pending" | "active" = "active"
) {
  return useBaseAPI(
    (id: number, memberStatus: "pending" | "active") =>
      classAPI.getClassMembers(id, memberStatus),
    { immediate: !!classId }
  );
}

/**
 * 删除班级Hook
 */
export function useDeleteClass() {
  return useBaseAPI((classId: number) => classAPI.deleteClass(classId), {
    showSuccess: true,
    successMessage: "班级删除成功",
  });
}

/**
 * 加入班级Hook
 */
export function useJoinClass() {
  return useBaseAPI((classId: number) => classAPI.joinClass(classId), {
    showSuccess: true,
    successMessage: "申请提交成功，等待教师审核",
  });
}

// =============================================================================
// 文件管理Hooks
// =============================================================================

/**
 * 文件上传Hook
 */
export function useFileUpload() {
  const [progress, setProgress] = useState(0);

  const upload = useBaseAPI(
    (file: File) => fileAPI.uploadFile(file, setProgress),
    { showSuccess: true, successMessage: "文件上传成功" }
  );

  return {
    ...upload,
    progress,
  };
}

/**
 * 获取文件列表Hook
 */
export function useFiles(classId?: number) {
  return useBaseAPI((id: number) => fileAPI.getFiles(id), {
    immediate: !!classId,
  });
}

/**
 * 添加文件Hook
 */
export function useAddFile() {
  return useBaseAPI((data: AddFileRequest) => fileAPI.addFile(data), {
    showSuccess: true,
    successMessage: "文件添加成功",
  });
}

/**
 * 发布文件Hook
 */
export function usePublishFile() {
  return useBaseAPI((fileId: number) => fileAPI.publishFile(fileId), {
    showSuccess: true,
    successMessage: "文件发布成功",
  });
}

/**
 * 删除文件Hook
 */
export function useDeleteFile() {
  return useBaseAPI((fileId: number) => fileAPI.deleteFile(fileId), {
    showSuccess: true,
    successMessage: "文件删除成功",
  });
}

// =============================================================================
// 建议反馈Hooks
// =============================================================================

/**
 * 获取建议列表Hook
 */
export function useAdviceList(classId?: number) {
  return useBaseAPI((id: number) => adviceAPI.getAdviceList(id), {
    immediate: !!classId,
  });
}

/**
 * 添加建议Hook
 */
export function useAddAdvice() {
  return useBaseAPI((data: AddAdviceRequest) => adviceAPI.addAdvice(data), {
    showSuccess: true,
    successMessage: "建议提交成功",
  });
}

/**
 * 反馈建议Hook
 */
export function useFeedbackAdvice() {
  return useBaseAPI(
    (adviceId: number, feedback: string) =>
      adviceAPI.feedbackAdvice({ adviceId, feedback }),
    { showSuccess: true, successMessage: "反馈提交成功" }
  );
}

// =============================================================================
// 考试管理Hooks
// =============================================================================

/**
 * 获取考试列表Hook
 */
export function useExams(classId?: number) {
  return useBaseAPI((id: number) => examAPI.getExams(id), {
    immediate: !!classId,
  });
}

/**
 * 添加考试Hook
 */
export function useAddExam() {
  return useBaseAPI((data: AddExamRequest) => examAPI.addExam(data), {
    showSuccess: true,
    successMessage: "考试创建成功",
  });
}

/**
 * 获取考试详情Hook
 */
export function useExamDetail(examId?: number) {
  return useBaseAPI((id: number) => examAPI.getExamDetail(id), {
    immediate: !!examId,
  });
}

// =============================================================================
// 话题讨论Hooks
// =============================================================================

/**
 * 获取话题列表Hook
 */
export function useTopics(
  params?: { classId?: number } & CommonQueryParams,
  immediate = false
) {
  return useBaseAPI(() => discussionAPI.getTopics(params || {}), {
    immediate,
  });
}

/**
 * 添加话题Hook
 */
export function useAddTopic() {
  return useBaseAPI((data: AddTopicRequest) => discussionAPI.addTopic(data), {
    showSuccess: true,
    successMessage: "话题发布成功",
  });
}

/**
 * 删除话题Hook
 */
export function useDeleteTopic() {
  return useBaseAPI((topicId: number) => discussionAPI.deleteTopic(topicId), {
    showSuccess: true,
    successMessage: "话题删除成功",
  });
}

/**
 * 点赞话题Hook
 */
export function useLikeTopic() {
  return useBaseAPI((topicId: number) => discussionAPI.likeTopic(topicId), {
    showSuccess: false,
  });
}

/**
 * 获取评论列表Hook
 */
export function useComments(topicId?: number) {
  return useBaseAPI(
    (id: number, page: number = 1, size: number = 10) =>
      discussionAPI.getComments(id, page, size),
    { immediate: !!topicId }
  );
}

/**
 * 添加评论Hook
 */
export function useAddComment() {
  return useBaseAPI(
    (data: AddCommentRequest) => discussionAPI.addComment(data),
    { showSuccess: true, successMessage: "评论发布成功" }
  );
}

/**
 * 删除评论Hook
 */
export function useDeleteComment() {
  return useBaseAPI(
    (commentId: number) => discussionAPI.deleteComment(commentId),
    { showSuccess: true, successMessage: "评论删除成功" }
  );
}

// =============================================================================
// AI相关Hooks
// =============================================================================

/**
 * AI聊天Hook
 */
export function useAIChat() {
  return useBaseAPI(
    (message: string, conversationId?: string) =>
      aiAPI.chat({ message, conversationId }),
    { showError: true }
  );
}

/**
 * AI流式聊天Hook
 */
export function useAIStreamChat() {
  const [messages, setMessages] = useState<string[]>([]);
  const [isStreaming, setIsStreaming] = useState(false);

  const startStream = useCallback(async (inputMessage: string) => {
    setIsStreaming(true);
    setMessages([]);

    try {
      const stream = await aiAPI.streamChat({ message: inputMessage });
      const reader = stream.getReader();

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        const chunk = new TextDecoder().decode(value);
        setMessages((prev) => [...prev, chunk]);
      }
    } catch (error: any) {
      message.error(error.message || "AI聊天失败");
    } finally {
      setIsStreaming(false);
    }
  }, []);

  return {
    messages,
    isStreaming,
    startStream,
  };
}

// =============================================================================
// 仪表板Hooks
// =============================================================================

/**
 * 仪表板统计Hook
 */
export function useDashboardStats(immediate = false) {
  return useBaseAPI(() => dashboardAPI.getStats(), { immediate });
}

// =============================================================================
// 健康检查Hooks
// =============================================================================

/**
 * 健康检查Hook
 */
export function useHealthCheck(immediate = false) {
  return useBaseAPI(() => healthAPI.checkHealth(), {
    immediate,
    showError: false,
    requireAuth: false, // 健康检查不需要认证
  });
}

/**
 * 认证检查Hook
 */
export function useAuthCheck(immediate = false) {
  return useBaseAPI(() => healthAPI.checkAuth(), {
    immediate,
    showError: false,
  });
}

// =============================================================================
// 批量操作Hooks
// =============================================================================

/**
 * 批量删除Hook
 */
export function useBatchDelete<T>(
  deleteFunction: (id: T) => Promise<void>,
  successMessage: string = "批量删除成功"
) {
  const [progress, setProgress] = useState(0);
  const [total, setTotal] = useState(0);

  const batchDelete = useBaseAPI(
    async (ids: T[]) => {
      setTotal(ids.length);
      setProgress(0);

      for (let i = 0; i < ids.length; i++) {
        await deleteFunction(ids[i]);
        setProgress(i + 1);
      }
    },
    { showSuccess: true, successMessage }
  );

  return {
    ...batchDelete,
    progress,
    total,
    percentage: total > 0 ? Math.round((progress / total) * 100) : 0,
  };
}

// =============================================================================
// 分页Hooks
// =============================================================================

/**
 * 分页Hook
 */
export function usePagination<T>(
  fetchFunction: (page: number, size: number) => Promise<T[]>,
  initialPageSize = 10
) {
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(initialPageSize);
  const [total, setTotal] = useState(0);

  const fetchData = useBaseAPI(
    async (currentPage: number, currentPageSize: number) => {
      const data = await fetchFunction(currentPage, currentPageSize);
      setTotal(data.length); // 实际应该从API响应中获取总数
      return data;
    }
  );

  const changePage = useCallback(
    (newPage: number, newPageSize?: number) => {
      setPage(newPage);
      if (newPageSize) {
        setPageSize(newPageSize);
      }
      fetchData.execute(newPage, newPageSize || pageSize);
    },
    [fetchData, pageSize]
  );

  useEffect(() => {
    fetchData.execute(page, pageSize);
  }, []);

  return {
    ...fetchData,
    page,
    pageSize,
    total,
    changePage,
    pagination: {
      current: page,
      pageSize,
      total,
      onChange: changePage,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: (total: number) => `共 ${total} 条记录`,
    },
  };
}
